//
//  YSReviewsCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/8/14.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//

#import "YSReviewsCtrl.h"
#import "YSReviewsHeaderView.h"
#import "YSReviewsDetailRes.h"
#import "YSHomeDataTool.h"
#import "YSReviewsComtCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "YSComtBottomView.h"
#import "YSReviewNavgationShareBar.h"
#import "YSClubDataTool.h"
#import "YSAccountCenterCtrl.h"
#import "YSAccountOrderStatusCtrl.h"
#import "AnimUtils.h"
#import "YSOrderViewCtrl.h"
#import "YSVirtualProtocol.h"
#import "YSCommonReqTool.h"
#import "CustomNavigationCtrl.h"
#import "YSSearchCtrl.h"

@interface YSReviewsCtrl ()<YSReviewsHeaderViewDelegate,UITableViewDelegate,UITableViewDataSource,YSComtBottomViewDelegate,YSAccountCenterDelegate,YSAccountOrderStatusDelegate>
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) YSReviewsDetailRes *result;
@property (strong, nonatomic) NSMutableArray *commentArray;
@property (strong, nonatomic) YSReviewsHeaderView *headerView;
@property (strong, nonatomic) YSReviews *reviews;
@property (strong, nonatomic) YSComtBottomView *bottomView;
@property (strong, nonatomic) YSReviewNavgationShareBar *shareBar;
@property(nonatomic,strong)UIImageView *animImage;
@property (strong, nonatomic) UIButton *backTopBtn;
@end

@implementation YSReviewsCtrl

+(instancetype)initWithReviews:(YSReviews *)reviews{
    YSReviewsCtrl *result = [[YSReviewsCtrl alloc]init];
    result.reviews = reviews;
    return result;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"悦食家"];
    _commentArray = [NSMutableArray array];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, YSReviewNavgationShareBarHeight, SCREENW, SCREENH-YSReviewNavgationShareBarHeight)];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerNib:[UINib nibWithNibName:@"YSReviewsComtCell" bundle:nil] forCellReuseIdentifier:@"YSReviewsComtCell"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView setHidden:YES];
    [self.view addSubview:_tableView];
    
    YSReviewsHeaderView *headerView = [[YSReviewsHeaderView alloc]init];
    headerView.reviewsId = self.reviews.id;
    [headerView setTitle:self.reviews.postName];
    [_tableView setTableHeaderView:headerView];
    _tableView.scrollsToTop = NO;
    _headerView = headerView;
    _headerView.delegate = self;
    
    _shareBar = [YSReviewNavgationShareBar shareBar];
    [_shareBar setX:0];
    [_shareBar setY:0];
    [_shareBar setWidth:SCREENW];
    [_shareBar.cartView addTarget:self action:@selector(tapCart:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_shareBar];
    
    if(self.reviews.reviewsType == YSReviewsVipType){
        self.fd_prefersNavigationBarHidden = YES;
        _shareBar.hidden = NO;
    }else{
        _shareBar.hidden = YES;
        self.fd_prefersNavigationBarHidden = NO;
        UIBarButtonItem *rightSearchItem = [UIBarButtonItem itemWithImageName:@"icon_home_search" highImageName:@"icon_home_search" target:self action:@selector(clickSearch)];
        self.navigationItem.rightBarButtonItem = rightSearchItem;
    }
    
    [self requestDataWithId:self.reviews.id lastComtId:0];
    
    _backTopBtn = [[UIButton alloc]init];
    _backTopBtn.frame = CGRectMake(SCREENW-50, self.view.height-100, 40, 40);
    [_backTopBtn setBackgroundImage:[UIImage imageNamed:@"icon_back_top"] forState:UIControlStateNormal];
    [_backTopBtn addTarget:self action:@selector(toTop:) forControlEvents:UIControlEventTouchUpInside];
    [_backTopBtn setHidden:YES];
    [self.view insertSubview:_backTopBtn aboveSubview:self.tableView];
    
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
}

- (void)clickSearch{
    //打开搜索界面
    CustomNavigationCtrl *nav = [[CustomNavigationCtrl alloc]initWithRootViewController:[[YSSearchCtrl alloc]init]];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

- (void)toTop:(UIButton *)toTopBtn{
    [UIView animateWithDuration:1.0 animations:^{
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    } completion:^(BOOL finished) {
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
    [self.bottomView setHidden:YES];
    [self.tableView setHeight:SCREENH-YSReviewNavgationShareBarHeight];
    
    if(scrollView.contentOffset.y > scrollView.height){
        [_backTopBtn setHidden:NO];
    }else{
        [_backTopBtn setHidden:YES];
    }
}

-(void)tapCart:(UIButton *)sender
{
    [Utils showCartCtrl:self];
}

-(void)footerRefresh{
    NSInteger lastcomtId = 0;
    if(self.commentArray.count){
        YSCommentInfo *comment =  [self.commentArray lastObject];
        lastcomtId = comment.commentId;
    }
    [self requestDataWithId:self.reviews.id lastComtId:lastcomtId];
}

-(void)requestDataWithId:(NSInteger)reviewsId lastComtId:(NSInteger)lastComtId{
    
    [YSHomeDataTool getReviewsDetailWithId:reviewsId lastComtId:lastComtId isLogin:ISLOGIN success:^(YSReviewsDetailRes *result) {
        [UIUtil refreshComplete:_tableView];
        if(result.isSucc){
            if (![_headerView haveData]) {
                _result = result;
                [_headerView setReviewsData:result.reviews prodList:result.productList];
                YSShareModel *sm = [YSShareModel new];
                [sm setUrl:result.reviews.shareLinks];
                [sm setImageUrl:result.reviews.imgList];
                [sm setTitle:result.reviews.postName];
                [sm setSubTile:result.reviews.summary];
                [_shareBar setShareModel:sm];
            }
            [_commentArray addObjectsFromArray:result.allComment];
            [self.tableView reloadData];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        [UIUtil refreshComplete:_tableView];
        ShowTips(kRequestFailure);
    }];
}

-(void)openComment{
    NSLog(@"%s",__func__);
    if(ISLOGIN){
        [self.bottomView setHidden:NO];
        [self.tableView setHeight:SCREENH-YSReviewNavgationShareBarHeight-self.bottomView.height];
    }else{
        [Utils showLoginCtrl:self];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (!self.bottomView) {
        YSComtBottomView *view = [YSComtBottomView bottomView];
        [view setDelegate:self];
        view.width = self.view.width;
        view.height = self.bottomView.height;
        view.y = SCREENH - view.height;
        [self.view addSubview:view];
        self.bottomView = view;
    }
    [self.bottomView setHidden:YES];
    [self.tableView setHeight:SCREENH-YSReviewNavgationShareBarHeight];
    
    if(self.shareBar.cartView){
        NSInteger num =  [DefaultsHelper integerForKey:kCartIndex];
        [self.shareBar.cartView setNum:num];
    }
}

-(void)keyboardWillChangeFrame:(NSNotification *)notif{
    // 1.获取键盘的Y值
    NSDictionary *dict  = notif.userInfo;
    CGRect keyboardFrame = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardY = keyboardFrame.origin.y;
    // 获取动画执行时间
    CGFloat duration = [dict[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    // 2.计算需要移动的距离
    CGFloat translationY = keyboardY - self.view.frame.size.height;
    [UIView animateWithDuration:duration delay:0.0 options:7 << 16 animations:^{
        // 需要执行动画的代码
        self.view.transform = CGAffineTransformMakeTranslation(0, translationY);
        CGFloat y = keyboardY - self.bottomView.height;
        
        y = y > self.view.height - self.bottomView.height
        ? self.view.height - self.bottomView.height
        :y-translationY;
        
        self.bottomView.y = y;
    } completion:^(BOOL finished) {
        // 动画执行完毕执行的代码
    }];
}

- (IBAction)tapAction:(id)sender {
    [self.view endEditing:YES];
}

-(void)publish:(NSString *)text{
    if(ISLOGIN){
        [self replyRecomment:text];
        //清空输入框
        self.bottomView.commentTextView.text = nil;
    }else{
        [Utils showLoginCtrl:self];
    }
}

-(void)replyRecomment:(NSString *)content{
    [YSHomeDataTool recommentWithReviewsId:self.reviews.id commentContent:content targetUserId:0 success:^(YSCommentRes *result) {
        if(result.isSucc){
            //评论成功
            YSCommentInfo *comment = [YSCommentInfo new];
            [comment setCommentId:result.commentId];
            [comment setCommentTime:@"1分钟前"];
            [comment setCommentContent:content];
            [comment setCommentName:[DefaultsHelper stringForKey:kNickName]];
            [comment setHeadImage:[DefaultsHelper stringForKey:kHeadImg]];
            [self.commentArray addObject:comment];
            [self.tableView reloadData];
            [self scrollToBottom];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
         ShowTips(kRequestFailure);
    }];
}

-(void)scrollToBottom{
    [self.tableView setHeight:SCREENH-YSReviewNavgationShareBarHeight];
    NSIndexPath *path = [NSIndexPath indexPathForRow:self.commentArray.count - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

#pragma Mark - tableview 数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _commentArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YSReviewsComtCell *cell =  [YSReviewsComtCell initWithTableView:tableView];
    [cell setCommentInfo:_commentArray[indexPath.row]];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView fd_heightForCellWithIdentifier:@"YSReviewsComtCell" cacheByIndexPath:indexPath configuration:^(YSReviewsComtCell *cell) {
        [cell setCommentInfo:self.commentArray[indexPath.row]];
    }];
}


- (void)webviewLoadFinish{
    [_tableView beginUpdates];
    [_tableView setTableHeaderView:_headerView];
    [_tableView endUpdates];
    [_tableView setHidden:NO];
}

- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
    NSMutableString *outputStr = [NSMutableString stringWithString:input];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@" "
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0, [outputStr length])];
    
    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

-(void)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *url = [self decodeFromPercentEscapeString:[request.URL absoluteString]];
    
    NSLog(@"url=%@",url);
    NSString *prefixStr  = @"yueshiopen://virtual?params=";
    if([url hasPrefix:prefixStr]){
        NSRange range =  [url rangeOfString:prefixStr];
        url = [url substringFromIndex:range.length];
        NSDictionary *params = [Utils dictionaryWithJsonString:url];
        YSVirtualProtocol *protocol = [YSVirtualProtocol objectWithKeyValues:params];
        if(protocol.linkType == YSVirtualProtocolAddCartProdMode){//加入购物篮
            [self requestProdDetail:protocol.entityId.integerValue type:NO];
        }else if(protocol.linkType == YSVirtualProtocolBuyProdMode){//立即购买
            [self requestProdDetail:protocol.entityId.integerValue type:YES];
        }
    }
}

//----------------以下为加入购物篮代码--------------//
/**
 *  请求商品信息
 *
 *  @param prodId 商品id
 *  @param type   是否是立即购买
 */
-(void)requestProdDetail:(NSInteger)prodId type:(BOOL)type{
    [YSClubDataTool getProductDetail:prodId isLogin:NO success:^(YSProductDetailRes *result) {
        if(result.isSucc){
            [self addToCart:result type:type];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure);
    }];
}

/**
 *  添加到购物篮
 *
 *  @param res  商品详情数据
 *  @param type 是否是立即购买
 */
-(void)addToCart:(YSProductDetailRes *)res type:(BOOL)type{
    if(ISLOGIN){
        [YSClubDataTool addCartWithParam:res.prodId prodCount:1 type:1 success:^(BaseResponse *result) {
            if(result.isSucc){
                if(type){//立即购买，跳转到结算中心,判断是否是体验券
                    AccountCenterProductType prodcutType = res.volume == 1?experienceProductType:ordinaryProductType;
                    
                    YSAccountCenterCtrl *ctrl =  [[YSAccountCenterCtrl alloc]initWithOrdreCode:nil selectProdIds:[NSString stringWithFormat:@"%ld",res.prodId] targetType:accountCenterFinishProductDetailType productType:prodcutType];
                    [ctrl setDelegate:self];
                    [self.navigationController pushViewController:ctrl animated:YES];
                }else{
                    [self startShopCartAnim:res];
                }
            }else{
                ShowEnterTips(result.data);
            }
        } failure:^(NSError *error) {
            ShowTips(kRequestFailure);
        }];
    }else{
        [Utils showLoginCtrl:self];
    }
}

-(void)startShopCartAnim:(YSProductDetailRes *)result{
    UIImage *image = [UIImage imageNamed:@"icon_add_cart"];
    _animImage = [[UIImageView alloc]initWithImage:image];
    _animImage.size = CGSizeMake(SCREENW/2, SCREENW/2);
    [_animImage.layer setCornerRadius:SCREENW/4];
    _animImage.layer.masksToBounds = YES;
    _animImage.center = self.view.center;
    [self.view addSubview:_animImage];
    [AnimUtils addToCartAnim:_animImage startView:self.view endView:_shareBar.cartView delegate:self adverse:-1];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    [_animImage removeFromSuperview];
    [self updateCartIndex];
}

-(void)updateCartIndex{
    //更新购物篮角标
    if(ISLOGIN){
        __weak typeof (self) weakSelf = self;
        [[YSCommonReqTool sharedTool] loadIndex:YSBadgeCartType callback:^(NSInteger count) {
            [weakSelf.shareBar.cartView setNum:count];
        }];
    }else{
        [DefaultsHelper setInteger:0 forKey:kCartIndex];
    }
}

/**
 *  结算中心页面关闭回调
 *
 *  @param type
 *  @param status
 */
-(void)accountCenterFinish:(int)type status:(NSString *)status{
    if(type == accountCenterFinishProductDetailType){
        [self toOrderStatusPage:status];
    }
}

/**
 *  跳转至支付状态页面
 *
 *  @param resultCode 状态码
 */
-(void)toOrderStatusPage:(NSString *)resultCode
{
    YSAccountOrderStatusCtrl *ctr = [YSAccountOrderStatusCtrl initWithResultCode:resultCode targetType:orderStatusFinishProductDetailType];
    ctr.delegate = self;
    //进入状态页面
    [self.navigationController pushViewController:ctr  animated:YES];
}

/**
 *  订单状态页面关闭,回调跳转至订单列表页
 *
 *  @param type
 */
-(void)orderStatusFinish:(int)type
{
    if(orderStatusFinishProductDetailType == type){
        [self.navigationController pushViewController:[YSOrderViewCtrl new] animated:YES];
    }
}

@end
